<?php

namespace app\common\model;

use think\Model;

class WechatUserModel extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'wechat_user';

    /**
     * 初始化关注用户数据
     * @param array $user_wx_data 用户微信数据
     * @return boolean
     */
    public function initUserData( array $user_wx_data ) {
        if ( !$user_wx_data ) {
            return false;
        }
        $open_id = $user_wx_data['openid'];
        $union_id = isset($user_wx_data['unionid']) ? $user_wx_data['unionid'] : '' ;

        $avatar = $user_wx_data['headimgurl'] ?: "";
        $city = $user_wx_data['city'];
        $country = $user_wx_data['country'];
        $nickname = $user_wx_data['nickname'];
        $province = $user_wx_data['province'];
        $sex = $user_wx_data['sex'];

        // 判断用户是否存在于微信公众号用户
        $map = array(
            'open_id' => $open_id,
            'union_id' => $union_id,
        );
        $user_wechat_data = $this->where($map)->find();
        if ( !$user_wechat_data ) {
            // 不存在,插入
            $insert_wechat_data = [
                'open_id' => $open_id,
                'union_id' => $union_id,
                'avatar' => $avatar,
                'nickname' => $nickname,
                'sex' => $sex,
                'country' => $country,
                'province' => $province,
                'city' => $city,
            ];
            $add_res = $this->insertGetId( $insert_wechat_data );
            if ( !$add_res ) {
                return false;
            }
            return $add_res;
        }
        return $user_wechat_data['id'];
    }

    /**
     * 删除关注用户数据
     * @param array $user_wx_data 用户微信数据
     * @return boolean
     */
    public function deleteUserData( array $user_wx_data ) {
        if ( !$user_wx_data ) {
            return false;
        }

        $open_id = $user_wx_data['openid'];

        // 判断用户是否存在于微信公众号用户
        $map = array(
            'open_id' => $open_id,
        );

        $this->where( $map )->find();

        return true;
    }

}
